package com.yixq.soa.service.comm.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * MQTT消息发送客户端
 * Created by marvin on 2017/4/24.
 */
public class DoorduMqttClient {

    private static String hostName = "tcp://mqtt.slb.doordu.com:1883";
    private static String clientId = "doordu-soa";

    public MqttClient getMqttClient() throws Exception{
        return new MqttClient(hostName, clientId, new MemoryPersistence());
    }

    public MqttClient getMqttClient(String hostName) throws Exception{
        return new MqttClient(hostName, clientId, new MemoryPersistence());
    }

    public void sendMsg(String hostName, String topic, String sendMsg) throws Exception{
        MqttClient client = this.getMqttClient(hostName);
        MqttConnectOptions options = new MqttConnectOptions();
//      options.setUserName(username);
//      options.setPassword(password.toCharArray());
        options.setCleanSession(true);
        options.setConnectionTimeout(10);
        // 设置会话心跳时间 单位为秒 服务器会每隔60秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(60);
        client.connect(options);
        boolean isSuccess = client.isConnected();
        System.out.println("连接状态:"+isSuccess);
        client.publish(topic, sendMsg.getBytes(), 2 , false);
        System.out.println("发送完毕");
        client.disconnect();
    }

//    public void disconnect() {
//        try {
//            client.disconnect();
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//    }

    public static void main(String args[]) throws Exception{
        String topic = "doordu/lgh";
        String sendMsg="{\"devices\":\""+75555+"\",\"payload\":{\"lgh\":\"李桂华测试MQTT\"}}";

        DoorduMqttClient doorduMqttClient = new DoorduMqttClient();
        doorduMqttClient.sendMsg(hostName, topic, sendMsg);
    }

}
